package tws

import (
	"go-web-scaffold/api"
	"log"
	"time"

	"github.com/gin-gonic/gin"
)

func AllowPrefix(prefix string) bool {
	prefixs := globalConfig.AllowPrefix
	instance := api.NewAllowPrefix()
	for _, prx := range prefixs {
		instance.Add(prx)
	}
	return instance.GetPrefix(prefix) != ""
}

var (
	limiter *api.RequestLimiter = api.NewRequestLimiter(10*time.Second, 5)
)

func RequestLimiter(ctx *gin.Context, callback func()) {
	if callback == nil {
		log.Fatal("callback is nil")
		return
	}
	if limiter.IsAvailable() {
		limiter.Increase()
	} else {
		callback()
		ctx.Abort()
		return
	}
	ctx.Next()
}

func Authorize(ctx *gin.Context, callback func()) {
	if callback == nil {
		log.Fatal("callback is nill")
		return
	}
	tokenString := ctx.GetHeader("Authorization")
	jwtToken := api.NewAuthorizeToken("tws")
	_, error := jwtToken.ParseTokenStirng(tokenString)
	if error != nil {
		callback()
		ctx.Abort()
		return
	}
	ctx.Next()
}

func WriteText(loggerInfo api.LoggerInfo) {
	logger := _writeLogger("text")
	logger.WriteLog(loggerInfo)
}

func WriteJson(loggerInfo api.LoggerInfo) {
	logger := _writeLogger("json")
	logger.WriteLog(loggerInfo)
}
func _writeLogger(output string) *api.RequestLogger {
	return api.NewRequestLogger(output, true)
}
